package com.xscha.tableforge.repository;

import com.xscha.soyue.common.core.utils.DateUtils;
import com.xscha.tableforge.model.entity.ViewMeta;
import com.xscha.tableforge.model.vo.PageReq;
import org.jooq.DSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.jooq.OrderField;
import org.jooq.Field;

import java.util.ArrayList;
import com.xscha.tableforge.model.vo.PageResult;
import java.util.List;
import java.util.Optional;

import static com.xscha.tableforge.jooq.tables.ViewMetaTable.VIEW_META;
import static org.jooq.impl.DSL.*;

@Repository
public class ViewMetaRepository {

	private final DSLContext dslContext;

	@Autowired
	public ViewMetaRepository(DSLContext dslContext) {
		this.dslContext = dslContext;
	}

	public List<ViewMeta> findAllByTableId(String tableId) {
		return dslContext.select()
				.from(VIEW_META)
				.where(VIEW_META.TABLE_ID.eq(tableId)
						.and(VIEW_META.DELETED_TIME.isNull()))
				.orderBy(VIEW_META.DISPLAY_ORDER.asc())
				.fetchInto(ViewMeta.class);
	}

	public Optional<ViewMeta> findById(String id) {
		return dslContext.select()
				.from(VIEW_META)
				.where(VIEW_META.ID.eq(id)
						.and(VIEW_META.DELETED_TIME.isNull()))
				.fetchOptionalInto(ViewMeta.class);
	}

	public ViewMeta save(ViewMeta viewMeta) {
		dslContext.insertInto(VIEW_META)
				.set(VIEW_META.ID, viewMeta.getId())
				.set(VIEW_META.NAME, viewMeta.getName())
				.set(VIEW_META.DESCRIPTION, viewMeta.getDescription())
				.set(VIEW_META.TABLE_ID, viewMeta.getTableId())
				.set(VIEW_META.TYPE, viewMeta.getType())
				.set(VIEW_META.SORT, viewMeta.getSort())
				.set(VIEW_META.FILTER, viewMeta.getFilter())
				.set(VIEW_META.GROUP, viewMeta.getGroup())
				.set(VIEW_META.OPTIONS, viewMeta.getOptions())
				.set(VIEW_META.DISPLAY_ORDER, viewMeta.getDisplayOrder())
				.set(VIEW_META.VERSION, viewMeta.getVersion())
				.set(VIEW_META.COLUMN_META, viewMeta.getColumnMeta())
				.set(VIEW_META.ENABLE_SHARE, viewMeta.getEnableShare())
				.set(VIEW_META.IS_DEFAULT, viewMeta.getIsDefault())
				.set(VIEW_META.SHARE_ID, viewMeta.getShareId())
				.set(VIEW_META.SHARE_META, viewMeta.getShareMeta())
				.set(VIEW_META.CREATED_TIME, viewMeta.getCreatedTime())
				.set(VIEW_META.CREATED_BY, viewMeta.getCreatedBy())
				.execute();
		return viewMeta;
	}

	public ViewMeta update(ViewMeta viewMeta) {
		dslContext.update(VIEW_META)
				.set(VIEW_META.NAME, viewMeta.getName())
				.set(VIEW_META.DESCRIPTION, viewMeta.getDescription())
				.set(VIEW_META.TYPE, viewMeta.getType())
				.set(VIEW_META.SORT, viewMeta.getSort())
				.set(VIEW_META.FILTER, viewMeta.getFilter())
				.set(VIEW_META.GROUP, viewMeta.getGroup())
				.set(VIEW_META.OPTIONS, viewMeta.getOptions())
				.set(VIEW_META.DISPLAY_ORDER, viewMeta.getDisplayOrder())
				.set(VIEW_META.VERSION, viewMeta.getVersion())
				.set(VIEW_META.COLUMN_META, viewMeta.getColumnMeta())
				.set(VIEW_META.ENABLE_SHARE, viewMeta.getEnableShare())
				.set(VIEW_META.IS_DEFAULT, viewMeta.getIsDefault())
				.set(VIEW_META.SHARE_ID, viewMeta.getShareId())
				.set(VIEW_META.SHARE_META, viewMeta.getShareMeta())
				.set(VIEW_META.LAST_MODIFIED_BY, viewMeta.getLastModifiedBy())
				.set(VIEW_META.LAST_MODIFIED_TIME, viewMeta.getLastModifiedTime())
				.where(VIEW_META.ID.eq(viewMeta.getId()))
				.execute();
		return viewMeta;
	}

	public void softDelete(String id, String userId) {
		dslContext.update(VIEW_META)
				.set(VIEW_META.DELETED_TIME, DateUtils.nowTimeStamp().toLocalDateTime())
				.set(VIEW_META.LAST_MODIFIED_BY, userId)
				.set(VIEW_META.LAST_MODIFIED_TIME, DateUtils.nowTimeStamp().toLocalDateTime())
				.where(VIEW_META.ID.eq(id))
				.execute();
	}

    public PageResult<ViewMeta> findPageByTableId(String tableId, PageReq pageRequest) {
        // 计算总记录数
        int total = dslContext.selectCount()
                .from(VIEW_META)
                .where(VIEW_META.TABLE_ID.eq(tableId)
                        .and(VIEW_META.DELETED_TIME.isNull()))
                .fetchOneInto(Integer.class);
        
        // 构建排序条件
        List<OrderField<?>> orderFields = new ArrayList<>();
        if (pageRequest.getOrderBy() != null && !pageRequest.getOrderBy().isEmpty()) {
            Field<?> orderField = VIEW_META.field(pageRequest.getOrderBy());
            if ("desc".equalsIgnoreCase(pageRequest.getOrderDirection())) {
                orderFields.add(orderField.desc());
            } else {
                orderFields.add(orderField.asc());
            }
        } else {
            // 默认按order字段排序
            orderFields.add(VIEW_META.DISPLAY_ORDER.asc());
        }
        
        // 查询分页数据
        List<ViewMeta> records = dslContext.select()
                .from(VIEW_META)
                .where(VIEW_META.TABLE_ID.eq(tableId)
                        .and(VIEW_META.DELETED_TIME.isNull()))
                .orderBy(orderFields)
                .limit(pageRequest.getPageSize())
                .offset((pageRequest.getPageNum() - 1) * pageRequest.getPageSize())
                .fetchInto(ViewMeta.class);
        
        return PageResult.of(records, total, pageRequest.getPageNum(), pageRequest.getPageSize());
    }
}